<?php
/**
 * 案件进度控制器
 */

declare (strict_types = 1);

namespace app\controller\lawcase;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Progress extends BaseController
{
    /**
     * 获取案件进度列表
     */
    public function list()
    {
        try {
            $param = Request::param();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 构建查询条件
            $where = [];
            $where[] = ['lp.delete_time', '=', 0];
            
            // 按案件ID筛选
            if (!empty($param['case_id'])) {
                $where[] = ['lp.case_id', '=', $param['case_id']];
            }
            
            // 按节点类型筛选
            if (!empty($param['event_type'])) {
                $where[] = ['lp.event_type', '=', $param['event_type']];
            }
            
            // 关键词搜索
            if (!empty($param['keywords'])) {
                $where[] = ['lp.content', 'like', '%' . trim($param['keywords']) . '%'];
            }
            
            // 查询案件进度列表
            $list = Db::name('lawcase_progress')
                ->alias('lp')
                ->join('lawcase l', 'lp.case_id = l.id', 'LEFT')
                ->join('admin a', 'lp.operator = a.id', 'LEFT')
                ->field('lp.*, l.case_code, a.name as operator_name')
                ->where($where)
                ->page($page, $limit)
                ->order('lp.event_time', 'desc')
                ->order('lp.id', 'desc')
                ->select()
                ->each(function($item) {
                    $item['event_time'] = $item['event_time'] ? date('Y-m-d', strtotime($item['event_time'])) : '';
                    $item['deadline'] = $item['deadline'] ? date('Y-m-d', strtotime($item['deadline'])) : '';
                    $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                    $item['update_time'] = $item['update_time'] ? date('Y-m-d H:i', $item['update_time']) : '';
                    
                    // 添加event_type_text字段，兼容历史数据
                    $item['event_type_text'] = $this->getEventTypeText($item['event_type']);
                    
                    return $item;
                });
            
            // 查询总数
            $count = Db::name('lawcase_progress')
                ->alias('lp')
                ->join('lawcase l', 'lp.case_id = l.id', 'LEFT')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看案件进度详情
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 查询案件进度详情
            $progress = Db::name('lawcase_progress')
                ->alias('lp')
                ->join('lawcase l', 'lp.case_id = l.id', 'LEFT')
                ->join('admin a', 'lp.operator = a.id', 'LEFT')
                ->field('lp.*, l.case_code, a.name as operator_name')
                ->where(['lp.id' => $param['id'], 'lp.delete_time' => 0])
                ->find();
            
            if (empty($progress)) {
                return json(['code' => 404, 'msg' => '案件进度不存在']);
            }
            
            // 格式化时间
            $progress['event_time'] = $progress['event_time'] ? date('Y-m-d', strtotime($progress['event_time'])) : '';
            $progress['deadline'] = $progress['deadline'] ? date('Y-m-d', strtotime($progress['deadline'])) : '';
            $progress['create_time'] = date('Y-m-d H:i', $progress['create_time']);
            $progress['update_time'] = $progress['update_time'] ? date('Y-m-d H:i', $progress['update_time']) : '';
            
            // 添加event_type_text字段，兼容历史数据
            $progress['event_type_text'] = $this->getEventTypeText($progress['event_type']);
            
            // 获取附件信息
            if (!empty($progress['attachment_ids'])) {
                $attachmentIds = json_decode($progress['attachment_ids'], true);
                if (is_array($attachmentIds) && !empty($attachmentIds)) {
                    $progress['attachments'] = Db::name('file')
                        ->where('id', 'in', $attachmentIds)
                        ->select()
                        ->toArray();
                }
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $progress
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 新增案件进度
     */
    public function add()
    {
        $param = Request::param();
        $userId = $this->getUserId();
        
        // 数据验证
        if (empty($param['case_id'])) {
            return json(['code' => 400, 'msg' => '案件ID不能为空']);
        }
        
        if (empty($param['event_type'])) {
            return json(['code' => 400, 'msg' => '流程节点不能为空']);
        }
        
        if (empty($param['event_time'])) {
            return json(['code' => 400, 'msg' => '事件时间不能为空']);
        }
        
        if (empty($param['content'])) {
            return json(['code' => 400, 'msg' => '事件描述不能为空']);
        }
        
        $data = [
            'case_id' => $param['case_id'],
            'event_type' => $param['event_type'],
            'event_time' => $param['event_time'],
            'content' => $param['content'],
            'deadline' => $param['deadline'] ?? '',
            'attachment_ids' => !empty($param['attachment_ids']) ? json_encode($param['attachment_ids']) : null,
            'operator' => $userId,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            // 新增案件进度
            $progressId = Db::name('lawcase_progress')->insertGetId($data);
            
            return json(['code' => 0, 'msg' => '保存成功', 'data' => ['id' => $progressId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '保存失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑案件进度
     */
    public function edit()
    {
        $param = Request::param();
        $userId = $this->getUserId();
        
        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        if (empty($param['event_type'])) {
            return json(['code' => 400, 'msg' => '流程节点不能为空']);
        }
        
        if (empty($param['event_time'])) {
            return json(['code' => 400, 'msg' => '事件时间不能为空']);
        }
        
        if (empty($param['content'])) {
            return json(['code' => 400, 'msg' => '事件描述不能为空']);
        }
        
        // 检查案件进度是否存在
        $progress = Db::name('lawcase_progress')
            ->where('id', $param['id'])
            ->where('delete_time', 0)
            ->find();
        
        if (!$progress) {
            return json(['code' => 404, 'msg' => '案件进度不存在']);
        }
        
        $data = [
            'id' => $param['id'],
            'event_type' => $param['event_type'],
            'event_time' => $param['event_time'],
            'content' => $param['content'],
            'deadline' => $param['deadline'] ?? $progress['deadline'],
            'attachment_ids' => !empty($param['attachment_ids']) ? json_encode($param['attachment_ids']) : $progress['attachment_ids'],
            'update_time' => time()
        ];
        
        try {
            // 更新案件进度
            Db::name('lawcase_progress')->update($data);
            
            return json(['code' => 0, 'msg' => '更新成功', 'data' => ['id' => $param['id']]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除案件进度（软删除）
     */
    public function delete()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 检查案件进度是否存在
            $progress = Db::name('lawcase_progress')
                ->where('id', $param['id'])
                ->where('delete_time', 0)
                ->find();
            
            if (!$progress) {
                return json(['code' => 404, 'msg' => '案件进度不存在']);
            }
            
            // 软删除案件进度
            Db::name('lawcase_progress')
                ->where('id', $param['id'])
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取指定案件的进度轴（按时间排序）
     */
    public function timeline()
    {
        $param = Request::param();
        
        if (empty($param['case_id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $list = Db::name('lawcase_progress')
                ->where('case_id', $param['case_id'])
                ->where('delete_time', 0)
                ->order('event_time', 'asc')
                ->order('id', 'asc')
                ->select()
                ->each(function($item) {
                    $item['event_time'] = $item['event_time'] ? date('Y-m-d', strtotime($item['event_time'])) : '';
                    $item['deadline'] = $item['deadline'] ? date('Y-m-d', strtotime($item['deadline'])) : '';
                    $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                    
                    // 添加event_type_text字段，兼容历史数据
                    $item['event_type_text'] = $this->getEventTypeText($item['event_type']);
                    
                    // 获取操作人信息
                    if ($item['operator'] > 0) {
                        $operator = Db::name('admin')
                            ->where('id', $item['operator'])
                            ->find();
                        $item['operator_name'] = $operator ? $operator['name'] : '';
                    }
                    
                    return $item;
                });
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取事件类型文本
     * 兼容处理历史数据中直接存储的文字和新的数字类型
     * 
     * @param string|int $eventType 事件类型
     * @return string
     */
    protected function getEventTypeText($eventType)
    {
        // 如果是字符串类型
        if (is_string($eventType)) {
            // 检查是否是纯数字字符串
            if (preg_match('/^\d+$/', $eventType)) {
                // 转换为数字处理
                $index = (int)$eventType;
                return $this->getEventTypeByIndex($index);
            }
            // 如果不是数字字符串，直接返回文字
            return $eventType;
        }
        
        // 如果是数字类型
        return $this->getEventTypeByIndex($eventType);
    }
    
    /**
     * 根据索引获取事件类型名称
     * 
     * @param int $index 事件类型索引（1-12）
     * @return string
     */
    protected function getEventTypeByIndex($index)
    {
        $eventTypes = [
            1 => '通知',
            2 => '进展',
            3 => '庭审',
            4 => '文书',
            5 => '任务',
            6 => '立案',
            7 => '提交材料',
            8 => '开庭',
            9 => '判决',
            10 => '执行',
            11 => '结案',
            12 => '其他'
        ];
        
        return isset($eventTypes[$index]) ? $eventTypes[$index] : (string)$index;
    }
}